<script setup lang="ts">
// 封装qtable组件 包括自定义分页器 第一列展示索引号
import { QTableColumn, QTable } from 'quasar';
import { quasarTableStyle } from '@/setting';
// QTable实例类型
type qTableInstance = InstanceType<typeof QTable>;
type qTableRequest = qTableInstance['onRequest'];
type onRequest = NonNullable<qTableRequest>;

// 定义props data columns pagination rowsPerPageOptions
// 类型声明
withDefaults(
  defineProps<{
    data: any[];
    columns: QTableColumn[];
    rowsPerPageOptions?: number[];
    usePagination?: boolean;
    useIndex?: boolean;
    loading?: boolean;
  }>(),
  {
    useIndex: true,
    usePagination: false,
    rowsPerPageOptions: () => [3, 5, 7]
  }
);
// model
interface Ipagination {
  page: number;
  rowsPerPage: number;
  rowsNumber: number;
  sortBy?: string;
  descending?: boolean;
}
const pagination = defineModel<Ipagination>('pagination');
// 定义emits
// const $emits = defineEmits(['getTableData']);
const emit = defineEmits<{
  getTableData: [page: number, rowsPerPage: number];
}>();

const tableRequest = async (props: Parameters<onRequest>[0]) => {
  const { page, rowsPerPage } = props.pagination;
  // 发送请求
  emit('getTableData', page, rowsPerPage);
  // 请求成功后更新分页相关数据
  pagination.value!.page = page;
  pagination.value!.rowsPerPage = rowsPerPage;
};
// 分页器当前页更新
function changePage(value: number) {
  pagination.value!.page = value;
  // qTable并为向外暴露方法
  // 手动调用tableRequest方法更新页面
  const params = {
    pagination: pagination.value,
    filter: '',
    getCellValue: function () {}
  };
  tableRequest(params as Parameters<onRequest>[0]);
}
</script>

<template>
  <q-table
    :separator="quasarTableStyle"
    :rows="data"
    :columns="columns"
    row-key="id"
    wrap-cells
    v-model:pagination="pagination"
    :rows-per-page-options="usePagination ? rowsPerPageOptions : [0]"
    @request="tableRequest"
    :loading="loading"
    :hide-pagination="!usePagination"
    v-bind="$attrs"
  >
    <!-- 序号插槽 -->
    <template v-slot:body-cell-index="props" v-if="useIndex">
      <q-td :props="props">{{ props.pageIndex + 1 }}</q-td>
    </template>
    <!-- 空数据 -->
    <template v-slot:no-data>
      <div class="full-width row flex-center q-py-md">
        <img src="@/assets/images/notData.png" style="width: 200px" />
      </div>
    </template>
    <!-- 渲染传入的所有插槽$slots -->
    <template v-for="(_slot, name) in $slots" v-slot:[name]="props">
      <slot :name="name" v-bind="props || {}" />
    </template>
    <!-- 分页器插槽 -->
    <template v-slot:pagination="scope" v-if="usePagination">
      <q-pagination
        v-model="scope.pagination.page"
        @update:model-value="changePage"
        :max="scope.pagesNumber"
        :max-pages="6"
        size="sm"
        direction-links
        boundary-numbers
      />
    </template>
  </q-table>
</template>

<style scoped>
/* code... */
</style>
